package com.akka.akkatry;

import java.io.DataInputStream;
import java.io.IOException;
import java.net.Socket;

/**
 * @author Dmitry
 */
public class SocketClient {
    public static int toInt(byte[] bytes, int offset) {
        int ret = 0;
        for (int i = 0; i < 4 && i + offset < bytes.length; i++) {
            ret <<= 8;
            ret |= (int) bytes[i] & 0xFF;
        }

        return ret;
    }

    public static void main(String[] args) throws IOException {
        Socket socket = new Socket("127.0.0.1", 8007);
        DataInputStream stream = new DataInputStream(socket.getInputStream());
        System.out.println("Client connected");
        int readCount = 0;
        int messagesCount = 0;
        long currentTime = System.currentTimeMillis();
        byte[] lengthBuffer = new byte[4];
        while (true) {
            stream.readFully(lengthBuffer);
            int length = toInt(lengthBuffer, 0);
            /* if (length > 100000) {
             System.out.println("Length is very big " + length);
             char c1 = (char) lengthBuffer[0];
             char c2 = (char) lengthBuffer[1];
             char c3 = (char) lengthBuffer[2];
             char c4 = (char) lengthBuffer[3];
             }*/
            readCount++;
            byte[] buffer = new byte[length];
            stream.readFully(buffer);
            messagesCount++;
            readCount += length;
            long time = System.currentTimeMillis();
            if (time - currentTime > 2000) {
                currentTime = time;
                long speed = readCount / 2;
                messagesCount /= 2;
                readCount = 0;
                System.out.println("ReadCount = " + (speed / (1024.0 * 1024.0)) + " message count = " + messagesCount);
                messagesCount = 0;
            }
        }
    }
}
